<!-- 回收站 -->
<template>
    <el-card shadow="always" :body-style="{ padding: '20px' }">
      <template #header>
        <el-row :gutter="20">
          <el-col :span="12">数据归档管理</el-col>
        </el-row>
      </template>
  
      <!-- 搜索栏 -->
      <div class="search-container">
        <el-form :inline="true" :model="searchForm" @submit.native.prevent>
          <el-form-item label="数据类型">
            <el-select v-model="searchForm.type" placeholder="选择数据类型" clearable>
              <el-option label="全部" value=""></el-option>
              <el-option label="用户" value="user"></el-option>
              <el-option label="宠物" value="pet"></el-option>
              <el-option label="文章" value="article"></el-option>
              <el-option label="帖子" value="post"></el-option>
            </el-select>
          </el-form-item>
  
          <el-form-item label="关键词">
            <el-input
              v-model="searchForm.keyword"
              placeholder="搜索标题或内容"
              @keyup.enter.native="handleSearch"
            ></el-input>
          </el-form-item>
  
          <el-form-item label="删除时间">
            <el-date-picker
              v-model="searchForm.dateRange"
              type="daterange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              value-format="yyyy-MM-dd"
            ></el-date-picker>
          </el-form-item>
  
          <el-form-item>
            <el-button type="primary" @click="handleSearch">搜索</el-button>
            <el-button @click="resetSearch">重置</el-button>
          </el-form-item>
        </el-form>
      </div>
  
      <!-- 数据表格 -->
      <el-table
        v-loading="loading"
        :data="archivesList"
        border
        style="width: 100%"
      >
        <el-table-column prop="id" label="ID" width="80" align="center" />
        
        <el-table-column label="数据类型" width="100" align="center">
          <template #default="{ row }">
            <el-tag :type="getTypeTag(row.type)">
              {{ getTypeLabel(row.type) }}
            </el-tag>
          </template>
        </el-table-column>
  
        <el-table-column prop="title" label="标题/名称" min-width="200" />
        
        <el-table-column label="删除时间" width="180" align="center">
          <template #default="{ row }">
            {{ formatDate(row.deleted_at) }}
          </template>
        </el-table-column>
  
        <el-table-column label="操作" width="200" align="center">
          <template #default="{ row }">
            <el-button
              size="small"
              type="success"
              @click="handleRestore(row)"
            >恢复</el-button>
            <el-button
              size="small"
              type="danger"
              @click="handleDelete(row)"
            >彻底删除</el-button>
          </template>
        </el-table-column>
      </el-table>
  
      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          background
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="currentPage"
          :page-sizes="[10, 20, 50]"
          :page-size="pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
        ></el-pagination>
      </div>
    </el-card>
  </template>
  
  <script>
  import { ref, reactive, onMounted } from 'vue'
  import { getArchives, restoreArchive, permanentDeleteArchive } from '@/api/archives'
  import { ElMessage, ElMessageBox } from 'element-plus'
  import dayjs from 'dayjs'
  
  export default {
    name: 'ArchivesSet',
    setup() {
      // 数据定义
      const loading = ref(false)
      const archivesList = ref([])
      const currentPage = ref(1)
      const pageSize = ref(10)
      const total = ref(0)
      
      const searchForm = reactive({
        type: '',
        keyword: '',
        dateRange: []
      })
  
      // 类型映射
      const typeMap = {
        user: { label: '用户', tag: 'info' },
        pet: { label: '宠物', tag: 'success' },
        article: { label: '文章', tag: 'warning' },
        post: { label: '帖子', tag: 'danger' }
      }
  
      // 获取数据列表
      // 修改获取数据列表方法
      const fetchData = async () => {
        loading.value = true
        try {
          const params = {
            page: currentPage.value,
            per_page: pageSize.value,
            type: searchForm.type,
            keyword: searchForm.keyword,
            start_date: searchForm.dateRange?.[0],
            end_date: searchForm.dateRange?.[1]
          }
  
          const response = await getArchives(params)
          if (response?.data?.code === 200) {
            archivesList.value = (response.data.data.items || []).map(item => ({
              ...item,
              // 直接使用后端返回的删除时间字段
              deleted_at: item.deleted_at || null
            }))
            total.value = response.data.data.total || 0
          } else {
            throw new Error(response?.data?.message || '获取数据失败')
          }
        } catch (error) {
          console.error('获取回收站数据失败:', error)
          ElMessage.error(error.message || '获取回收站数据失败，请稍后重试')
        } finally {
          loading.value = false
        }
      }
  
      // 搜索处理
      const handleSearch = () => {
        currentPage.value = 1
        fetchData()
      }
  
      // 重置搜索
      const resetSearch = () => {
        searchForm.type = ''
        searchForm.keyword = ''
        searchForm.dateRange = []
        handleSearch()
      }
  
      // 恢复数据
      const handleRestore = async (row) => {
        try {
          await ElMessageBox.confirm(
            `确定要恢复这条${getTypeLabel(row.type)}数据吗？`,
            '提示',
            {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              type: 'warning',
              closeOnClickModal: false,
              closeOnPressEscape: false
            }
          )
  
          loading.value = true
          const response = await restoreArchive(row.id)
          if (response && response.data && response.data.code === 200) {
            ElMessage.success('数据恢复成功')
            await fetchData() // 重新加载数据
          } else {
            throw new Error(response?.data?.message || '恢复失败')
          }
        } catch (error) {
          if (error !== 'cancel' && error.message !== 'cancel') {
            console.error('恢复数据失败:', error)
            ElMessage.error(error.message || '数据恢复失败，请稍后重试')
          }
        } finally {
          loading.value = false
        }
      }
  
      // 彻底删除
      const handleDelete = async (row) => {
        try {
          await ElMessageBox.confirm(
            `确定要彻底删除这条${getTypeLabel(row.type)}数据吗？此操作不可恢复！`,
            '警告',
            {
              confirmButtonText: '彻底删除',
              cancelButtonText: '取消',
              type: 'error',
              closeOnClickModal: false,
              closeOnPressEscape: false
            }
          )
  
          loading.value = true
          const response = await permanentDeleteArchive(row.id)
          if (response && response.data && response.data.code === 200) {
            ElMessage.success('数据删除成功')
            await fetchData() // 重新加载数据
          } else {
            throw new Error(response?.data?.message || '删除失败')
          }
        } catch (error) {
          if (error !== 'cancel' && error.message !== 'cancel') {
            console.error('删除数据失败:', error)
            ElMessage.error(error.message || '数据删除失败，请稍后重试')
          }
        } finally {
          loading.value = false
        }
      }
  
      // 工具方法
      const getTypeLabel = (type) => typeMap[type]?.label || type
      const getTypeTag = (type) => typeMap[type]?.tag || ''
      const formatDate = (date) => dayjs(date).format('YYYY-MM-DD HH:mm:ss')
  
      // 分页处理
      const handleSizeChange = (val) => {
        pageSize.value = val
        fetchData()
      }
  
      const handleCurrentChange = (val) => {
        currentPage.value = val
        fetchData()
      }
  
      // 初始化
      onMounted(() => {
        fetchData()
      })
  
      return {
        loading,
        archivesList,
        currentPage,
        pageSize,
        total,
        searchForm,
        handleSearch,
        resetSearch,
        handleRestore,
        handleDelete,
        getTypeLabel,
        getTypeTag,
        formatDate,
        handleSizeChange,
        handleCurrentChange
      }
    }
  }
  </script>
  
  <style scoped>
  .search-container {
    margin-bottom: 20px;
  }
  
  .pagination-container {
    margin-top: 20px;
    text-align: right;
  }
  </style>